const pool = require('../models/db');

const articleController = {
    // 获取所有文章
    getAllArticles: async (req, res) => {
        try {
            // 获取所有查询参数
            const {
                page = 1,
                pageSize = 10,
                tag_id,
                category_id,
                author_id,
                status,
                search  // 搜索参数
            } = req.query;

            // 转换分页参数
            const pageNum = parseInt(page);
            const limit = parseInt(pageSize);
            const offset = (pageNum - 1) * limit;

            // 构建查询条件
            let whereClause = '1 = 1';
            const queryParams = [];

            // 标签筛选
            if (tag_id) {
                whereClause += ' AND at.tag_id = ?';
                queryParams.push(parseInt(tag_id));
            }

            // 分类筛选
            if (category_id) {
                whereClause += ' AND a.category_id = ?';
                queryParams.push(parseInt(category_id));
            }

            // 作者筛选
            if (author_id) {
                whereClause += ' AND a.author_id = ?';
                queryParams.push(parseInt(author_id));
            }

            // 状态筛选
            if (status) {
                whereClause += ' AND a.status = ?';
                queryParams.push(status);
            }

            // 搜索功能 - 不区分大小写
            if (search) {
                whereClause += ` AND (
                    LOWER(a.title) LIKE LOWER(?) OR 
                    LOWER(a.description) LIKE LOWER(?) OR 
                    LOWER(t.name) LIKE LOWER(?)
                )`;
                const searchKeyword = `%${search}%`;
                queryParams.push(searchKeyword, searchKeyword, searchKeyword);
            }

            // 获取总数
            const [total] = await pool.query(`
                SELECT COUNT(DISTINCT a.id) as total
                FROM articles a
                LEFT JOIN article_tags at ON a.id = at.article_id
                LEFT JOIN tags t ON at.tag_id = t.id
                WHERE ${whereClause}
            `, queryParams);

            // 获取分页数据
            const [articles] = await pool.query(`
                SELECT DISTINCT a.*, 
                       u.username as author_name,
                       c.name as category_name,
                       GROUP_CONCAT(DISTINCT t.name) as tags
                FROM articles a
                LEFT JOIN users u ON a.author_id = u.id
                LEFT JOIN categories c ON a.category_id = c.id
                LEFT JOIN article_tags at ON a.id = at.article_id
                LEFT JOIN tags t ON at.tag_id = t.id
                WHERE ${whereClause}
                GROUP BY a.id
                ORDER BY a.created_at DESC
                LIMIT ? OFFSET ?
            `, [...queryParams, limit, offset]);

            // 处理标签
            articles.forEach(article => {
                article.tags = article.tags ? article.tags.split(',') : [];
                // 如果没有缩略图，使用默认图片
                if (!article.thumbnail_url) {
                    article.thumbnail_url = 'http://localhost:3000/public/image/avatar.jpg';
                }
            });

            // 返回分页数据
            res.json({
                total: total[0].total,
                page: pageNum,
                pageSize: limit,
                totalPages: Math.ceil(total[0].total / limit),
                data: articles,
                search: search || '' // 返回搜索关键词
            });

        } catch (error) {
            console.error('Error fetching articles:', error);
            res.status(500).json({ error: error.message });
        }
    },

    // 获取单篇文章
    getArticleById: async (req, res) => {
        try {
            const id = parseInt(req.params.id);
            if (isNaN(id)) {
                return res.status(400).json({ message: '无效的文章ID' });
            }

            const [articles] = await pool.query(`
                SELECT a.*, 
                       u.username as author_name,
                       c.name as category_name,
                       GROUP_CONCAT(t.name) as tags
                FROM articles a
                LEFT JOIN users u ON a.author_id = u.id
                LEFT JOIN categories c ON a.category_id = c.id
                LEFT JOIN article_tags at ON a.id = at.article_id
                LEFT JOIN tags t ON at.tag_id = t.id
                WHERE a.id = ?
                GROUP BY a.id
            `, [id]);

            if (articles.length === 0) {
                return res.status(404).json({ message: '文章不存在' });
            }

            const article = articles[0];
            article.tags = article.tags ? article.tags.split(',') : [];
            // 如果没有缩略图，使用默认图片
            if (!article.thumbnail_url) {
                article.thumbnail_url = 'http://localhost:3000/public/image/avatar.jpg';
            }

            res.json(article);
        } catch (error) {
            res.status(500).json({ error: error.message });
        }
    },

    // 创建文章
    createArticle: async (req, res) => {
        try {
            const { 
                title, content, description, 
                author_id, category_id, tags, 
                status = 'draft' 
            } = req.body;
            // 设置默认缩略图
            const thumbnail_url = req.body.thumbnail_url || 'http://localhost:3000/public/image/avatar.jpg';
            const connection = await pool.getConnection();
            try {
                await connection.beginTransaction();

                // 插入文章
                const [result] = await connection.query(
                    `INSERT INTO articles 
                    (title, content, description, thumbnail_url, author_id, category_id, status)
                    VALUES (?, ?, ?, ?, ?, ?, ?)`,
                    [title, content, description, thumbnail_url, author_id, category_id, status]
                );

                // 如果有标签，处理文章标签关联
                if (tags && tags.length > 0) {
                    for (const tagName of tags) {
                        // 获取或创建标签
                        const [existingTag] = await connection.query(
                            'SELECT id FROM tags WHERE name = ?',
                            [tagName]
                        );

                        let tagId;
                        if (existingTag.length === 0) {
                            const [newTag] = await connection.query(
                                'INSERT INTO tags (name) VALUES (?)',
                                [tagName]
                            );
                            tagId = newTag.insertId;
                        } else {
                            tagId = existingTag[0].id;
                        }

                        // 关联文章和标签
                        await connection.query(
                            'INSERT INTO article_tags (article_id, tag_id) VALUES (?, ?)',
                            [result.insertId, tagId]
                        );
                    }
                }

                // 更新分类的文章计数
                await connection.query(
                    'UPDATE categories SET article_count = article_count + 1 WHERE id = ?',
                    [category_id]
                );

                await connection.commit();
                res.status(201).json({
                    message: '文章创建成功',
                    articleId: result.insertId
                });
            } catch (error) {
                await connection.rollback();
                throw error;
            } finally {
                connection.release();
            }
        } catch (error) {
            res.status(500).json({ error: error.message });
        }
    },

    // 更新文章
    updateArticle: async (req, res) => {
        try {
            const { 
                title, content, description,
                category_id, tags, status 
            } = req.body;
            const articleId = req.params.id;
            // 设置默认缩略图
            const thumbnail_url = req.body.thumbnail_url || 'http://localhost:3000/public/image/avatar.jpg';
            const connection = await pool.getConnection();
            try {
                await connection.beginTransaction();

                // 更新文章基本信息
                const [result] = await connection.query(
                    `UPDATE articles 
                    SET title = ?, content = ?, description = ?, 
                        thumbnail_url = ?, category_id = ?, status = ?
                    WHERE id = ?`,
                    [title, content, description, thumbnail_url, category_id, status, articleId]
                );

                if (result.affectedRows === 0) {
                    await connection.rollback();
                    return res.status(404).json({ message: '文章不存在' });
                }

                // 如果提供了新的标签，更新标签关联
                if (tags) {
                    // 删除旧的标签关联
                    await connection.query(
                        'DELETE FROM article_tags WHERE article_id = ?',
                        [articleId]
                    );

                    // 添加新的标签关联
                    for (const tagName of tags) {
                        const [existingTag] = await connection.query(
                            'SELECT id FROM tags WHERE name = ?',
                            [tagName]
                        );

                        let tagId;
                        if (existingTag.length === 0) {
                            const [newTag] = await connection.query(
                                'INSERT INTO tags (name) VALUES (?)',
                                [tagName]
                            );
                            tagId = newTag.insertId;
                        } else {
                            tagId = existingTag[0].id;
                        }

                        await connection.query(
                            'INSERT INTO article_tags (article_id, tag_id) VALUES (?, ?)',
                            [articleId, tagId]
                        );
                    }
                }

                await connection.commit();
                res.json({ message: '文章更新成功' });
            } catch (error) {
                await connection.rollback();
                throw error;
            } finally {
                connection.release();
            }
        } catch (error) {
            res.status(500).json({ error: error.message });
        }
    },

    // 删除文章
    deleteArticle: async (req, res) => {
        try {
            const connection = await pool.getConnection();
            try {
                await connection.beginTransaction();

                // 获取文章信息
                const [article] = await connection.query(
                    'SELECT category_id FROM articles WHERE id = ?',
                    [req.params.id]
                );

                if (article.length === 0) {
                    await connection.rollback();
                    return res.status(404).json({ message: '文章不存在' });
                }

                // 删除文章
                await connection.query(
                    'DELETE FROM articles WHERE id = ?',
                    [req.params.id]
                );

                // 更新分类的文章计数
                await connection.query(
                    'UPDATE categories SET article_count = article_count - 1 WHERE id = ?',
                    [article[0].category_id]
                );

                await connection.commit();
                res.json({ message: '文章删除成功' });
            } catch (error) {
                await connection.rollback();
                throw error;
            } finally {
                connection.release();
            }
        } catch (error) {
            res.status(500).json({ error: error.message });
        }
    },

    // 增加浏览量
    incrementViewCount: async (req, res) => {
        try {
            const [result] = await pool.query(
                'UPDATE articles SET view_count = view_count + 1 WHERE id = ?',
                [req.params.id]
            );

            if (result.affectedRows === 0) {
                return res.status(404).json({ message: '文章不存在' });
            }

            res.json({ message: '浏览量更新成功' });
        } catch (error) {
            res.status(500).json({ error: error.message });
        }
    },

    // 点赞/取消点赞
    toggleLike: async (req, res) => {
        try {
            const [result] = await pool.query(
                'UPDATE articles SET like_count = like_count + 1 WHERE id = ?',
                [req.params.id]
            );

            if (result.affectedRows === 0) {
                return res.status(404).json({ message: '文章不存在' });
            }

            res.json({ message: '点赞成功' });
        } catch (error) {
            res.status(500).json({ error: error.message });
        }
    }
};

module.exports = articleController;